package com.example.democrud.common.file.excel.parse.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.Builder;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IAnalysisEventListener
 * @Author Administrator
 * @Date 2020/4/27   17:05
 */
public class IAnalysisEventListener<T,R extends IService<T>> extends AnalysisEventListener<T> {
    private static final Logger log = LoggerFactory.getLogger(IAnalysisEventListener.class);
    private int batchCount = 5;
    List<T> list = new ArrayList<>();
    private R baseService;

    public IAnalysisEventListener(R baseService){
        this.baseService = baseService;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.info("解析到一条数据：{}", JSON.toJSONString(data));
        list.add(data);
        if(list.size()>=batchCount){
            saveDate();
            //存储完list清楚
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveDate();
        log.info("所有数据解析完成!");
    }

    private void saveDate(){
        log.info("{}条数据开始存储数据库!",list.size());
        baseService.saveBatch(list);
        log.info("数据库存储成功!");
    }

    public int getBatchCount(){
        return this.batchCount;
    }

    public IAnalysisEventListener  setBatchCount(int batchCount){
        this.batchCount = batchCount;
        return  this;
    }
}
